package com.cskaoyan.service;

import com.cskaoyan.bean.MarketAdmin;
import com.cskaoyan.bean.MarketAdminExample;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.util.AuthenticationUtil;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.StringUtil;
import com.cskaoyan.util.TransactionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.*;

/**
 * @author stone
 * @date 2023/03/17 10:32
 */
public class AdminServiceImpl implements AdminService {
/*    private static SqlSession sqlSession;
    private static MarketAdminMapper marketAdminMapper;
    private static SqlSessionFactory sqlSessionFactory;

    static {
        sqlSession = TransactionUtil.getSqlSession();
        marketAdminMapper = sqlSession.getMapper(MarketAdminMapper.class);
        sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
    }*/

    @Override
    public MarketAdmin query(String username, String password) {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketAdminMapper mapper = sqlSession.getMapper(MarketAdminMapper.class);
        MarketAdminExample example = new MarketAdminExample();
        example.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<MarketAdmin> marketAdmins = mapper.selectByExample(example);
        sqlSession.commit();
        if (marketAdmins != null && marketAdmins.size() == 1) {
            return marketAdmins.get(0);
        }
        sqlSession.close();
        return null;
    }

    //查
    @Override
    public BaseRespVo list(Integer page, Integer limit, String username, String sort, String order) {
        //开启事务
        TransactionUtil.startTransaction();
        MarketAdminMapper marketAdminMapper = TransactionUtil.getMapper(MarketAdminMapper.class);

        //分页
        PageHelper.startPage(page, limit);

        //构造条件子句
        MarketAdminExample example = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtil.isEmpty(username)) {
            criteria.andUsernameEqualTo(username);
        }
        criteria.andDeletedEqualTo(false);
        if (!StringUtil.isEmpty(sort) & !StringUtil.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        //执行查询
        List<MarketAdmin> marketAdminList = marketAdminMapper.selectByExample(example);

        //返回响应对象
        TransactionUtil.commit();
        return BaseRespVo.ok(CommonData.data(new PageInfo(marketAdminList)));
    }

    //增
    @Override
    public BaseRespVo create(MarketAdmin marketAdmin) {
        //启动事务
        TransactionUtil.startTransaction();
        MarketAdminMapper marketAdminMapper = TransactionUtil.getMapper(MarketAdminMapper.class);

        //检测传参错误
        BaseRespVo error = checkUsername(marketAdmin.getUsername());
        if (error != null) {
            return error;
        }

        //执行插入
        marketAdmin.setAddTime(new Date());
        marketAdmin.setDeleted(false);
        int updateCount = marketAdminMapper.insertSelective(marketAdmin);

        //返回响应对象
        MarketAdminExample example = new MarketAdminExample();
        example.setOrderByClause("add_time desc");
        List<MarketAdmin> marketAdminList = marketAdminMapper.selectByExample(example);
        TransactionUtil.commit();
        if (updateCount != 0) {
            return BaseRespVo.ok(marketAdminList.get(0));
        }
        return BaseRespVo.fail("创建失败");
    }

    //改
    @Override
    public BaseRespVo update(MarketAdmin marketAdmin) {
        //启动事务
        TransactionUtil.startTransaction();
        MarketAdminMapper marketAdminMapper = TransactionUtil.getMapper(MarketAdminMapper.class);

        //检测传参错误
        BaseRespVo error = checkUsername(marketAdmin.getUsername());
        if (error != null) {
            return error;
        }

        //执行更新
        marketAdmin.setUpdateTime(new Date());
        int updateCount = marketAdminMapper.updateByPrimaryKeySelective(marketAdmin);

        //返回响应对象
        TransactionUtil.commit();
        if (updateCount != 0) {
            return BaseRespVo.ok(marketAdmin);
        }
        return BaseRespVo.fail("修改失败");
    }

    //删
    @Override
    public BaseRespVo delete(MarketAdmin marketAdmin) {
        //开启事务
        TransactionUtil.startTransaction();
        MarketAdminMapper marketAdminMapper = TransactionUtil.getMapper(MarketAdminMapper.class);

        //执行更新
        marketAdmin.setDeleted(true);
        int updateCount = marketAdminMapper.updateByPrimaryKeySelective(marketAdmin);

        //返回响应对象
        TransactionUtil.commit();
        if (updateCount != 0) {
            return BaseRespVo.ok(marketAdmin);
        }
        return BaseRespVo.fail("删除失败");
    }

    @Override
    public BaseRespVo modifyPassword(Map passwordMap) {
        //开始事务
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketAdminMapper marketAdminMapper = sqlSession.getMapper(MarketAdminMapper.class);

        //获取参数
        String oldPassword = passwordMap.get("oldPassword").toString();
        String newPassword = passwordMap.get("newPassword").toString();
        String newPassword2 = passwordMap.get("newPassword2").toString();

        //检测传参错误
        if (StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(newPassword2))
            return BaseRespVo.fail(401, "请输入必填项");
        if (!newPassword.equals(newPassword2))
            return BaseRespVo.fail(401, "两次输入新密码请保持一致");

        //找到当前管理员名
        MarketAdmin marketAdmin = (MarketAdmin) AuthenticationUtil.getPrincipal();
        String username = marketAdmin.getUsername();
        MarketAdmin currentAdmin = new AdminServiceImpl().query(username, oldPassword);

        //密码输入错误
        if (currentAdmin == null) {
            return BaseRespVo.fail(401, "原密码输入错误");
        }

        //密码输入正确
        marketAdmin.setPassword(newPassword);
        marketAdmin.setUpdateTime(new Date());

        MarketAdminExample example = new MarketAdminExample();
        example.createCriteria().andUsernameEqualTo(username).andDeletedEqualTo(false);
        int updateCount = marketAdminMapper.updateByExampleSelective(marketAdmin, example);

        sqlSession.commit();
        sqlSession.close();
        TransactionUtil.commit();
        if (updateCount != 0) {
            return BaseRespVo.ok(marketAdmin);
        }
        return BaseRespVo.fail("修改失败");
    }

    //方法：检测传参错误
    @SneakyThrows
    private BaseRespVo checkUsername(String username) {
        if (!username.matches("^[a-zA-Z0-9_-]*$"))
            return BaseRespVo.fail(401, "管理员名非法，只能包含字母数字、下划线和破折号");
        if (username.getBytes("utf-8").length < 6)
            return BaseRespVo.fail(401, "管理员名不能小于6字符");
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketAdminMapper marketAdminMapper = sqlSession.getMapper(MarketAdminMapper.class);
        MarketAdminExample example = new MarketAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<MarketAdmin> marketAdminList = marketAdminMapper.selectByExample(example);
        if (marketAdminList != null || marketAdminList.size() == 0 || marketAdminList.get(0) != null)
            //其实是一个长度为0的数组
            return BaseRespVo.fail(401, "管理员名已存在");
        return null;
    }
}